<!--房间列表页-->
<template>
  <el-container>
    <el-header height="8vh" style="padding: 10px 20px;background-color: #fff;overflow:hidden;">
      <span style="line-height: 60px;font-size: 20px;">房间管理</span>
      <el-form :inline="true" style="float: right;margin-top: 10px;">
        <el-form-item label="店家选择" style="width: 220px;">
          <el-select v-model="roomQuery.shopId"
                     placeholder="请选择店家" @change="loadRoom">
            <el-option v-for="shop in merchant.shopList"
                       :label="shop.shopName" :value="shop.id"/>
          </el-select>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main style="padding: 0;">
      <el-card style="height: 70px;margin: 20px;">
        <el-form :inline="true">
          <el-form-item label="房间是否展示" style="width: 220px;">
            <el-select v-model="roomQuery.visible"
                       placeholder="请选择" @change="loadRoom">
              <el-option v-for="item in visibleEnum"
                         :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadRoom">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card style="margin: 20px;">
        <div style="margin:10px 0 40px 10px;">
          房间列表
          <el-button style="float: right;margin-top:-3px;" type="primary"
                     @click="showAddRoom">
            新增房间
          </el-button>
        </div>
        <el-table
            :data="roomList"
            style="width: 100%">
          <el-table-column align="center" label="序号" type="index" width="80"/>
          <el-table-column align="center" label="房间id" prop="id"/>
          <el-table-column align="center" label="房间名称" prop="name"/>
          <el-table-column align="center" label="房间描述" prop="description"/>
          <el-table-column align="center" label="房间价格（元/小时）" prop="price"
                           width="100"/>
          <el-table-column align="center" label="房间大小" prop="size"/>
          <el-table-column align="center" label="房间标签" prop="tagNameString"/>
          <el-table-column :formatter="openingHoursFormatter" align="center"
                           label="营业时间"/>
          <el-table-column :formatter="visibleFormatter" align="center"
                           label="是否展示" prop="visible"/>
          <el-table-column align="center" label="平均评分" prop="avgRating"
                           width="80"/>
          <el-table-column align="center" label="月订单数" prop="orderNum"
                           width="80"/>
          <el-table-column align="center" label="操作" width="150">
            <template #default="scope">
              <el-button link type="primary"
                         @click="showEditRoom(scope.row.id)">编辑
              </el-button>
              <el-button link type="primary"
                         @click="showRoomDetail(scope.row)">详情
              </el-button>
              <el-button link type="danger"
                         @click="deleteRoom(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>

  <el-dialog
      v-model="showDialogVisible"
      :before-close="closeShowDialog"
      style="padding: 40px;"
      title="房间详情"
      width="1000px">
    <el-descriptions :column="2" border direction="horizontal">
      <el-descriptions-item label="房间id">
        {{ roomDetail.id }}
      </el-descriptions-item>
      <el-descriptions-item label="房间名称">
        {{ roomDetail.name || null }}
      </el-descriptions-item>

      <el-descriptions-item label="房间描述">
        {{ roomDetail.description || null }}
      </el-descriptions-item>
      <el-descriptions-item label="房间价格（元/小时）">
        {{ roomDetail.price || null }}
      </el-descriptions-item>

      <el-descriptions-item label="房间大小">
        {{ roomDetail.size || null }}
      </el-descriptions-item>
      <el-descriptions-item label="房间标签">
        {{ roomDetail.tagNameString || null }}
      </el-descriptions-item>

      <el-descriptions-item label="营业时间">
        {{ roomDetail.openingHoursFrom || null }}
        - {{ roomDetail.openingHoursTo || null }}
      </el-descriptions-item>
      <el-descriptions-item label="是否展示">
        {{ getRoomVisible }}
      </el-descriptions-item>

      <el-descriptions-item label="房间图片">
        <el-image v-if="roomDetail?.imgUrlList
        && roomDetail.imgUrlList.length > 0"
            style="width: 250px; height: 150px"
            :src="roomDetail.imgUrlList[0]"
            :max-scale="7" :min-scale="0.2"
            :preview-src-list="roomDetail.imgUrlList"
            :initial-index="4" :zoom-rate="1.2"
            fit="contain"/>
      </el-descriptions-item>
      <el-descriptions-item label="房间视频">
        <video v-if="roomDetail?.video" :src="roomDetail.video"
               controls height="150px" width="250px"/>
      </el-descriptions-item>

      <el-descriptions-item label="创建时间">
        {{ roomDetail.createTime }}
      </el-descriptions-item>
      <el-descriptions-item label="平均评分">
        {{ roomDetail.avgRating || null }}
      </el-descriptions-item>

      <el-descriptions-item label="月订单数">
        {{ roomDetail.orderNum || null }}
      </el-descriptions-item>
      <el-descriptions-item label="点赞数">
        {{ roomDetail.likes || null }}
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="closeShowDialog">返回</el-button>
    </template>
  </el-dialog>

  <el-dialog
      v-model="editDialogVisible"
      :before-close="handleCloseEdit"
      :title="isAdd ? '新建房间' : '编辑房间'"
      style="padding: 40px;"
      width="1000px">
    <el-form label-position="top" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间id">
            <el-input v-model="roomDetail.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间名称">
            <el-input v-model="roomDetail.name" placeholder="请输入房间名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间描述">
            <el-input v-model="roomDetail.description"
                      placeholder="请输入房间描述"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间价格（元/小时）">
            <el-input v-model="roomDetail.price" placeholder="请输入房间价格"
                      step="0.01" type="number"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间大小">
            <el-input v-model="roomDetail.size"
                      placeholder="请输入房间大小"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间标签">
            <el-scrollbar style="width: 100%"
                          view-style="min-width:0"
                          wrap-style="display:flex; white-space:nowrap">
              <el-tag v-for="(tagId,index) in roomDetail.tagIdList" :key="tagId" closable
                      style="margin:0 10px 20px 0;"
                      type="success"
                      @close="closeTag(index)">
                {{ getTagName(tagId) }}
              </el-tag>
              <!--@input="getTagSuggest(tagInputValue)"-->
              <el-autocomplete v-if="tagInputVisible" v-model="tagInputValue"
                               :fetch-suggestions="querySearch"
                               clearable placeholder="请输入标签名"
                               size="small" style="margin:0 10px 20px 0;width: 100px"
                               @change=""
                               @clear="hiddenTagInput" @select="selectTag"
                               @keydown.enter="selectTag(tagSuggestionArr[0])"/>
              <el-button v-else class="button-new-tag"
                         size="small"
                         style="margin:0 10px 20px 0;" @click="showTagInput">
                + 新标签
              </el-button>
            </el-scrollbar>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="营业时间">
            <el-time-picker v-model="roomDetail.timeRange"
                            end-placeholder="关门" is-range="is-range"
                            start-placeholder="开门" value-format="HH:mm"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否展示">
            <el-radio-group v-model="roomDetail.visible">
              <el-radio v-for="item in visibleEnum"
                        :label="item.label" :value="item.value"/>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="房间图片">
            <el-upload
                v-model:file-list="imgList"
                :action="uploadAction" :on-success="pictureAdd"
                :on-preview="handlePictureCardPreview"
                :on-remove="handlePictureRemove"
                list-type="picture-card">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房间视频">
            <el-upload
                v-model:file-list="videoFileList" :action="uploadAction"
                :before-upload="beforeVideoUpload" :limit="1"
                :on-exceed="()=>ElMessage.error('只能上传一个文件')" :on-remove="handleRemove"
                accept=".mp4,.avi" :on-success="videoAdd">
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div>
                  只能上传一个小于500MB的 MP4/AVI 文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleCloseEdit">取消</el-button>
      <el-button type="primary"
                 @click="saveRoom">保存房间
      </el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="imageDialogVisible">
    <img :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import qs from "qs";

const merchant = ref({
  shopList: [],
});
const roomQuery = ref({
  shopId: null,
  visible: null,
})
const roomList = ref([])
let tagIdSet = new Set();
const tagList = ref([])
const visibleEnum = ref([
  {label: '展示', value: '1'},
  {label: '不展示', value: '0'},
])
const roomDetail = ref({});
const showDialogVisible = ref(false);
const editDialogVisible = ref(false);
const isAdd = ref(false);
const tagInputVisible = ref(false);
const tagInputValue = ref('');
let tagSuggestionArr = [];
const tagQuery = ref({
  fuzzySearchIs: true,
  recursionUp: true,
  recursionDown: true,
});
const imgList = ref([]);
const uploadAction = ref(BASE_URL + 'v1/file/upload');
const imageDialogVisible = ref(false);
const dialogImageUrl = ref('');
const videoFileList = ref([]);

onMounted(() => {
  getMerchant(merchant);
});
const loadRoom = () => {
  if (roomQuery.value.shopId == null) {
    ElMessage.info("请选择店家");
    return;
  }
  let data = qs.stringify(roomQuery.value);
  axios.get(BASE_URL + 'v1/show/room/select?' + data)
      .then(res => {
        if (res.data.code === 2000) {
          roomList.value = res.data.data;
          setTagNameString(roomList.value);
        } else {
          ElMessage.error(res.data.msg);
        }
      });
}
const setTagNameString = async (roomArr) => {
  // console.log(roomArr);
  if (roomArr == null || roomArr.length === 0) {
    return;
  }
  for (let room of roomArr) {
    if (room.tagIdList == null || room.tagIdList.length === 0) {
      continue;
    }
    tagIdSet =
        new Set([...tagIdSet, ...room.tagIdList]);
  }
  if (tagIdSet.size !== tagList.value.length) {
    await updateTagEnum();
  }
  for (let room of roomArr) {
    // console.log(tagList);
    if (room.tagIdList == null || room.tagIdList.length === 0) {
      continue;
    }
    room.tagNameList = [];
    for (let id of room.tagIdList) {
      let name = getTagName(id);
      if (!name) {
        continue;
      }
      room.tagNameList.push(name);
    }
    room.tagNameString = room.tagNameList.join(',');
    // console.log(room.tagNameList);
  }
}
const updateTagEnum = async () => {
  // console.log(tagIdSet);
  let data = {tagIdList: tagIdSet.size ? [...tagIdSet] : []};
  // console.log(data);
  try {
    let res = await axios.get(BASE_URL + 'v1/show/tag/select/ids',
        {
          params: data, paramsSerializer:
              params => qs.stringify(params, {indices: false})
        });
    if (res.data.code === 2000) {
      tagList.value = res.data.data;
      // console.log('tagList');
      // console.log(tagList.value);
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
}
const getTagName = (id) => {
  // console.log(id);
  // console.log(tagList.value);
  if (!tagList.value) {
    return null;
  }
  for (let tag of tagList.value) {
    if (tag.id === id) {
      return tag.label;
    }
  }
  return null;
}
const resetSearch = () => {
  roomQuery.value.visible = null;
  loadRoom();
}
const openingHoursFormatter = (row, column, cellValue, index) => {
  const start = row.openingHoursFrom;
  const end = row.openingHoursTo;
  return `${start} - ${end}`;
}
const visibleFormatter = (row, column, cellValue, index) => {
  return cellValueFormatter(cellValue, visibleEnum);
}
const showAddRoom = () => {
  if (roomQuery.value.shopId == null) {
    ElMessage.info("请选择店家");
    return;
  }
  isAdd.value = true;
  editDialogVisible.value = true;
  roomDetail.value = {
    shopId: roomQuery.value.shopId,
    visible: '0',
    tagIdList: [],
    tagNameList: [],
    imgUrlList: [],
  }
}
const showEditRoom = async (id) => {
  let res = await axios.get(BASE_URL + 'v1/show/room/select',
      {params: {id: id}});
  if (res.data.code === 2000) {
    let roomArr = res.data.data;
    await setTagNameString(roomArr);
    roomDetail.value = roomArr[0];
    // console.log(roomDetail.value);
  } else {
    ElMessage.error(res.data.msg);
    return;
  }
  roomDetail.value.timeRange = [
    roomDetail.value.openingHoursFrom,
    roomDetail.value.openingHoursTo
  ];
  // console.log(roomDetail.value.timeRange);
  let list = roomDetail.value.imgUrlList;
  // console.log(list);
  if (list != null && list.length > 0) {
    for (let imgUrl of list) {
      if (imgUrl != null && imgUrl.trim() !== '') {
        imgList.value.push({
          name: imgUrl,
          url: imgUrl,
        })
      }
    }
    // console.log(imgList.value);
  }
  let video = roomDetail.value.video;
  // console.log(video);
  if (video != null && video.trim() !== '') {
    videoFileList.value.push({
      name: video,
      url: video,
    })
    // console.log(videoFileList.value);
  }
  editDialogVisible.value = true;
}
const showRoomDetail = (row) => {
  roomDetail.value = row;
  showDialogVisible.value = true;
}
const deleteRoom = (row) => {
  if (!confirm('是否删除房间：' + row.name + '？')) {
    return;
  }
  axios.post(BASE_URL + 'v1/show/room/delete/' + row.id)
      .then(res => {
        if (res.data.code === 2000) {
          ElMessage.success('已删除');
          loadRoom();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
}
const closeShowDialog = () => {
  showDialogVisible.value = false;
  roomDetail.value = {};
}
const getRoomVisible = computed(() => {
  return cellValueFormatter(roomDetail.value.visible, visibleEnum);
})
const handleCloseEdit = () => {
  if (confirm('是否放弃编辑？')) {
    closeEditDialog();
  }
}
const closeEditDialog = () => {
  editDialogVisible.value = false;
  roomDetail.value = {};
  videoFileList.value = [];
  imgList.value = [];
  isAdd.value = false;
}
const closeTag = (index) => {
  roomDetail.value.tagIdList.splice(index, 1);
}
const showTagInput = () => {
  tagInputVisible.value = true;
}
const hiddenTagInput = () => {
  tagInputVisible.value = false;
  tagInputValue.value = '';
  tagSuggestionArr = [];
}
const querySearch = (queryString, cb) => {
  // 根据 queryString 过滤数据
  getTagSuggest(queryString);
  cb(tagSuggestionArr); // 回调函数返回匹配结果
};
const getTagSuggest = async (queryString) => {
  if (!queryString || queryString === '') {
    tagSuggestionArr = [];
    return;
  }
  tagQuery.value.label = queryString;
  // console.log(tagQuery.value);
  let res = await axios.get(BASE_URL + 'v1/show/tag/select',
      {params: tagQuery.value});
  if (res.data.code === 2000) {
    tagSuggestionArr = res.data.data;
    if (tagSuggestionArr != null
        && tagSuggestionArr.length > 0) {
      for (let tag of tagSuggestionArr) {
        tag.value = tag.label;
      }
    }
  } else {
    ElMessage.error(res.data.msg);
  }
}
const selectTag = (tag) => {
  console.log(tagSuggestionArr);
  if (tag == null) {
    return;
  }
  roomDetail.value.tagIdList.push(tag.id);
  roomDetail.value.tagNameList.push(tag.label);
  tagIdSet.add(tag.id);
  tagList.value.push(tag);
  hiddenTagInput();
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  imageDialogVisible.value = true
}
const pictureAdd = (response, uploadFile) => {
  roomDetail.value.imgUrlList.push(response.data);
}
const videoAdd = (response, uploadFile) => {
  roomDetail.value.video = response.data;
}
const handlePictureRemove = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  handleRemove(uploadFile, 1);
}
const handleRemove = (uploadFile, field) => {
  let filePath;
  if (!uploadFile.response) {
    filePath = uploadFile.url;
  } else {
    filePath = uploadFile.response.data;
  }
  if (!filePath) {
    return;
  }
  axios.delete(BASE_URL + '/v1/file/delete',
      {params: {filePath: filePath}})
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功！');
          if (field === 1) {
            let list = roomDetail.value.imgUrlList;
            list = list.filter(item => item!==filePath);
            roomDetail.value.imgUrlList = list;
          } else {
            roomDetail.value.video = null;
          }
        } else {
          ElMessage.error(response.data.message);
        }
      });
}
const beforeVideoUpload = (rawFile) => {
  // console.log(rawFile);
  // console.log(videoFile.value);
  const ext = rawFile.name.split('.').pop().toLowerCase();
  // console.log(ext);
  if (!['mp4', 'avi'].includes(ext)
      || (rawFile.type !== 'video/mp4'
          && rawFile.type !== 'video/x-msvideo')) {
    // console.log(111111111111111111111111111111)
    ElMessage.error("文件格式只能是MP4或者AVI");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 500) {
    ElMessage.error("文件不能大于500MB");
    return false;
  }
  return true;
}
const saveRoom = () => {
  // console.log(videoFileList.value);
  // console.log(imgList.value);
  roomDetail.value.openingHoursFrom =
      roomDetail.value.timeRange[0];
  roomDetail.value.openingHoursTo =
      roomDetail.value.timeRange[1];
  axios.post(BASE_URL + 'v1/show/room/save', roomDetail.value)
  .then(res => {
    if (res.data.code === 2000) {
      ElMessage.success('保存成功！');
      closeEditDialog();
      loadRoom();
    } else {
      ElMessage.error(res.data.message);
    }
  });
}
</script>

<style scoped>

</style>